package com.yima.baseproj.module.app.equipment_entry;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.base.Charsets;
import com.yima.baseproj.config.exception.type.ApiException;
import com.yima.baseproj.module.app.Controller.model.DetailModel;
import com.yima.baseproj.module.app.equipmentDevice.EquipmentDeviceService;
import com.yima.baseproj.module.app.equipmentEquipment.EquipmentEquipmentService;
import com.yima.baseproj.module.app.gentable.util.StringUtils;
import com.yima.baseproj.module.config.BaseController;
import com.yima.baseproj.module.config.utils.PageUtil;
import com.yima.baseproj.module.config.utils.PageVo;
import com.yima.baseproj.module.app.equipment_entry.model.*;
import com.yima.baseproj.utils.CacheUtil;
import com.yima.baseproj.utils.Error.MessageConstant;
import com.yima.baseproj.utils.HttpClientUtil;
import com.yima.baseproj.utils.R;
import com.yima.baseproj.utils.StringToJsonConverter;
import com.yima.baseproj.utils.excel.UserExcel;
import com.yima.baseproj.utils.excel.UserImportListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;


/**
 * 录入设备
 *
 * @author 一码
 * @createDate 2024-02-04 14:23:38
 * @contact 1424529270@qq.com
 **/
@Slf4j
@Api(tags = "录入设备")
@RestController
@RequestMapping("api/equipment/entry")
public class EquipmentEntryController extends BaseController {

    @Resource
    private EquipmentEntryService equipmentEntryService;
    @Resource
    private EquipmentDeviceService equipmentDeviceService;
    @Resource
    private EquipmentEquipmentService equipmentEquipmentService;

    @ApiOperation("查询分页")
    @GetMapping(value = "/findAllByPage")
    public Object findAllByPage(PageVo page, EquipmentEntrySearchModel searchVo) {
        Page<Map> pageData = equipmentEntryService.findByPage(PageUtil.initMpPage(page), searchVo);
        return pageData;
    }

    @ApiOperation("查询列表")
    @GetMapping(value = "/findAllByList")
    public Object findAllByList(EquipmentEntrySearchModel searchVo) {
        List<Map> list = equipmentEntryService.findByList(searchVo);
        return list;
    }

    @ApiOperation("查询详情")
    @GetMapping(value = "/findById/{id}")
    public Map findById(@PathVariable String id) {
        EquipmentEntryEntity equipmentEntryEntity = equipmentEntryService.getById(id);
        if (equipmentEntryEntity == null) {
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }

        Map result = JSON.parseObject(JSON.toJSONString(equipmentEntryEntity), Map.class);

        return result;
    }

    @ApiOperation("添加")
    @PostMapping(value = "/add")
    public void add(@Validated @RequestBody EquipmentEntryAddParamModel paramModel) {
        //方式一：适合单一添加
        EquipmentEntryEntity equipmentEntryEntity = new EquipmentEntryEntity();
        equipmentEntryEntity.setData(paramModel);
        equipmentEntryService.save(equipmentEntryEntity);

        //方法二：适合事务添加
//        equipmentEntryService.add(paramModel);
    }

    @ApiOperation("修改")
    @PostMapping(value = "/edit")
    public void edit(@Validated @RequestBody EquipmentEntryEditParamModel paramModel) {
        //校验参数
        EquipmentEntryEntity equipmentEntryEntity = equipmentEntryService.getById(paramModel.getId());
        if (equipmentEntryEntity == null) {
            throw new ApiException("数据不存在，请刷新重试");
        }

        //方式一：适合单一编辑
        equipmentEntryEntity.setData(paramModel);
        equipmentEntryService.updateById(equipmentEntryEntity);

        //方法二：适合事务编辑
//        equipmentEntryService.edit(paramModel);
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/delByIds/{ids}")
    public void delAllByIds(@PathVariable String[] ids) throws Exception {
        List<String> idList = Arrays.asList(ids);
        String result = String.join(", ", idList);
        EquipmentEntryEntity equipmentEntryEntity = equipmentEntryService.getById(result);

        String url = "/v2/device/delete";
        DetailModel detailModel = new DetailModel();
        detailModel.setSource("000000");
        detailModel.setDeviceNo(equipmentEntryEntity.getDeviceNo());
        String JsonData = StringToJsonConverter.convertToJson(detailModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, "52A5A9157E3942AE830EFC1D6AB2A86F");
        JSONObject jsonObject = new JSONObject(response);
        String msg = jsonObject.getString("msg");
        if (msg.contains("success")) {
            boolean del = equipmentEquipmentService.delNO(detailModel.getDeviceNo());
            boolean equipmentDeviceDel = equipmentDeviceService.delNO(detailModel.getDeviceNo());
            System.out.println("del:------" + del);
            System.out.println("equipmentDeviceDel:------" + equipmentDeviceDel);
            if (del && equipmentDeviceDel) {
                equipmentEntryService.dels(ids);
            }
        }
        //适合事务删除

    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {

        //从数据库查出所有的数据
        List<EquipmentEntryEntity> list = equipmentEntryService.list();
        //在内存操作写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("deviceNo", "设备序列号");
        writer.addHeaderAlias("count", "备注");

        //一次性写出list对象到Excel使用默认样式，强制输出标题
        writer.write(list, true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officeedocument.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("设备序列号导入数据", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }


    /**
     * 导入接口
     */
    @PostMapping("/import")
    public String imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //直接读数据表的内容
        List<List<Object>> list = reader.read(1);
        //使用hutool里面的工具类
        List<EquipmentEntryEntity> infantMessages = CollUtil.newArrayList();
        for (List<Object> row : list) {
            EquipmentEntryEntity infantMessage = new EquipmentEntryEntity();
            infantMessage.setDeviceNo(row.get(1).toString());
            infantMessage.setCount(row.get(2).toString());
            infantMessages.add(infantMessage);
        }
        equipmentEntryService.saveBatch(infantMessages);
        return "成功";
    }
}